﻿using Microsoft.Extensions.Configuration;
using SHFK.B2C.YouZanYun.Network;
using SHKF.B2C.Model;
using SHKF.B2C.YouZanYun.BLL;
using SHKF.B2C.YouZanYun.Model.Dto.Token;
using SHKF.B2C.YouZanYun.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SHKF.B2C.YouZanYun.ServiceS
{
    /// <summary>
    /// 单实店的访问
    /// </summary>
    public class HttpClientYouZanYun : HttpClientYzy
    {
        private readonly TokenBLL tokenBLL;
        
        public HttpClientYouZanYun(IConfiguration configuration, 
            TokenBLL tokenBLL)
        {
            this.tokenBLL = tokenBLL; 
            this.authority_id = configuration.GetSection("authority_id").Value; 
        }

        protected async override Task<TokenYZYDto> GetToken()
        { 
            TokenYZYDto requestToken = null;
            DateTime now = DateTime.Now;
            long timestamp = DateTimeUtil.DateTimeToLongTimeStamp(now.AddHours(1)); //一小时误差

            try
            {
                //数据库存在
                requestToken = this.GetErpToken();

                if (requestToken == null)
                {
                    requestToken = await GetYouZanYunToken(false);
                    if (requestToken.code == 200)
                    {
                        this.SaveErpToken(requestToken);
                    }
                }
                else
                {
                    if (requestToken.Data != null && requestToken.Data.expires <= timestamp) //如果access_token过期
                    {
                        //刷新    
                        //if (requestToken.Data.re_expires <= timestamp) //如果刷新时间也过期了,需要重新申请店铺，这是极端事件，需要手动去有赞云
                        //{
                        //    requestToken = await GetYouZanYunToken(false);
                        //    if (requestToken.code > 0)
                        //    {
                        //        requestToken = null;
                        //        this.access_token = "";

                        //        throw new Exception("refresh_expires:如果刷新refresh_expires也过期了,需要重新申请店铺，这是极端事件，需要手动去有赞云的平台操作");
                        //    }
                        //}
                        //else //如果refresh_token没有过期，重新刷新
                        //{
                        requestToken = await GetYouZanYunToken(true);
                        if (requestToken.code == 200)
                        {
                            this.SaveErpToken(requestToken);
                        }
                        //}
                    }
                    else
                    {
                        requestToken.code = 200;
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            return requestToken;
        }

        private TokenYZYDto GetErpToken()
        {
            TokenYZYDto dto = null; 
            try
            {
                TokenEntity requestToken = this.tokenBLL.Get(authority_id);
                if (requestToken != null)
                {
                    TokenDataDto token = new TokenDataDto();
                    token.expires = requestToken.expires;
                    token.re_expires = requestToken.re_expires;
                    token.scope = requestToken.scope;
                    token.access_token = requestToken.access_token;
                    token.refresh_token = requestToken.refresh_token;
                    token.authority_id = requestToken.authority_id;
                    TokenYZYDto tokenDto = new TokenYZYDto();
                    tokenDto.message = "";
                    tokenDto.code = 0;
                    tokenDto.Data = token;

                    this.access_token = requestToken.access_token;
                    return tokenDto;
                }

                return null;
            }
            catch (Exception ex)
            {
                dto = new TokenYZYDto();
                dto.message = ex.Message;
                dto.code = -1;
            }

            return dto;
        }

        private void SaveErpToken(TokenYZYDto requestToken)
        {
            try
            {
                TokenDataDto data = requestToken.Data;

                TokenEntity info = new TokenEntity();
                info.access_token = data.access_token;
                info.expires = data.expires;
                info.refresh_token = data.refresh_token;
                info.re_expires = data.re_expires;
                info.scope = "";
                info.authority_id = data.authority_id;

                this.tokenBLL.Save(info);
            }
            catch (Exception ex)
            { 
                throw ex;
            }
           
        }

    }
}
